package pl.wroc.uni.ii.gdomo;

import java.sql.SQLException;
import java.util.List;

import pl.wroc.uni.ii.gdomo.data.DatabaseHelper;
import pl.wroc.uni.ii.gdomo.data.HighScore;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.j256.ormlite.android.AndroidConnectionSource;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.support.ConnectionSource;

public class HighScoresActivity extends Activity {

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);	
		setContentView(R.layout.high_score);
		setHighScoreList();
	}

	private void setHighScoreList() {
		List<HighScore> highScoreList;
		try {
			highScoreList = retrieveHighScoreList();
			fillViewWithHighScoreList(highScoreList);
		} catch (SQLException e) {
			Log.e(HighScoresActivity.class.getName(), "can't receive data from base", e);
		}
	}
	
	private void fillViewWithHighScoreList(List<HighScore> highScoreList) {
		ListView listView = (ListView)findViewById(R.id.highScoreListView);
		String[] highScoreArray = new String[highScoreList.size()];
		int i = 0;
		for (HighScore hs : highScoreList) {
			highScoreArray[i] = hs.toString();
			i++;
		}
		ArrayAdapter<String> aa = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , highScoreArray);
		listView.setAdapter(aa);
	}

	private List<HighScore> retrieveHighScoreList() throws SQLException {

		DatabaseHelper databaseHelper = new DatabaseHelper(this);
		ConnectionSource connectionSource = new AndroidConnectionSource(databaseHelper);
		Dao<HighScore, Integer> highScoreDao = DaoManager.createDao(connectionSource, HighScore.class);
		List<HighScore> highScores = highScoreDao.queryForAll();
		connectionSource.close();
		return highScores;
	}	
}
